package controllers

import (
	"fmt"
	"io"
	"math/rand"
	"myapp/config"
	"myapp/pkg"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

func UploadFileHandler(ossClient *pkg.OSSClient) gin.HandlerFunc {
	return func(c *gin.Context) {
		file, header, err := c.Request.FormFile("file")
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "上传文件失败: " + err.Error()})
			return
		}
		defer file.Close()

		// 获取当前时间
		currentTime := time.Now()
		yearMonth := currentTime.Format("200601") // 按年/月分目录
		// 随机生成一个字符串（可以更改生成规则）
		randomStr := fmt.Sprintf("%d", rand.Intn(1000000))
		// 获取文件扩展名
		ext := strings.ToLower(filepath.Ext(header.Filename))

		// 根据时间戳和随机字符串生成文件名
		fileName := fmt.Sprintf("%d%s%s", currentTime.Unix(), randomStr, ext)

		// 创建目录，如果不存在
		dir := filepath.Join("uploads", yearMonth)
		err = os.MkdirAll(config.Conf.UploadRoot+dir, os.ModePerm)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"code": 1, "msg": "无法创建目录: " + err.Error()})
			return
		}

		// 创建目标文件
		dstFilePath := filepath.Join(dir, fileName)
		dstFile, err := os.Create(config.Conf.UploadRoot + dstFilePath)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"code": 1, "msg": "无法创建文件: " + err.Error()})
			return
		}
		defer dstFile.Close()

		// 将上传的文件写入本地文件
		_, err = io.Copy(dstFile, file)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"code": 1, "msg": "文件保存失败: " + err.Error()})
			return
		}

		// 返回文件的存储路径或URL
		c.JSON(http.StatusOK, gin.H{"code": 0, "url": "/" + dstFilePath})

		/*
			url, err := ossClient.UploadFile(file, header.Filename)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "上传到OSS失败: " + err.Error()})
				return
			}

		c.JSON(http.StatusOK, gin.H{"url": url})*/
	}
}
